package com.beiding.businessplatform.data;

import java.util.*;

public class ListSubVmUnit implements CacheUnit<List<? extends Vm>> {

    private Vm vm;

    private String field;

    private List<? extends Vm> subVms;

    public ListSubVmUnit(Vm vm, String field) {
        this.vm = vm;
        this.field = field;
    }

    @Override
    public void write(Set<Vm> vmPath) {

        vmPath.add(vm);

        HolderMap map = vm.holderMap();

        Holder holder = map.get(this.field);

        List<Be> obes = (List<Be>) holder.get();
        List<Be> bes = obes;

        if (bes == null) {
            if (subVms != null) {
                //TODO 构建成
                bes = new ArrayList<>();
                for (Vm subVm : subVms) {
                    if (vmPath.contains(subVm)) {
                        continue;
                    }
                    Be rb = subVm.vmCache().handle(vmPath);
                    bes.add(rb);
                }
                holder.set(bes);
            }
        } else {
            if (subVms == null) {
                holder.set(null);
            } else {
                //当前的列表
                Map<String, Be> mapping = new HashMap<>();
                for (Be b : bes) {
                    if (b.getId() != null) {
                        mapping.put(b.getId(), b);
                    }
                }
                //TODO 列表
                bes = new ArrayList<>();
                for (Vm subVm : subVms) {
                    if (vmPath.contains(subVm)) {
                        bes.add(subVm.be());
                        continue;
                    }
                    String id = subVm.getId();
                    if (id != null) {
                        Be b = mapping.get(id);
                        if (b != null) {
                            Be targetBe = subVm.be();
                            if (targetBe != b) {
                                subVm.vmCache().handle(b, vmPath);
                            }
                            bes.add(b);
                        } else {
                            b = subVm.vmCache().handle(vmPath);
                            bes.add(b);
                        }
                    }

                }

                if (!bes.equals(obes)) {
                    //TODO 内容放入
                    holder.set(bes);
                }
            }
        }

        vmPath.remove(vm);

    }

    @Override
    public List<? extends Vm> read() {
        return subVms;
    }


    public void update(List<? extends Vm> value) {
        this.subVms = value;
        write(new HashSet<>());
    }

    public void setSubVms(List<? extends Vm> subVms) {
        this.subVms = subVms;
    }
}
